import { Button, Descriptions, message, Table, Pagination, Checkbox, Col, Row, Radio, Popconfirm, Image  } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { ProFormTextArea, ModalForm, ProFormRadio } from '@ant-design/pro-form';
import { paperList, sysList, questionDelete, listByLevel, getValueAndTextList, addBatch, downloadSgf } from './service'
import { history } from 'umi';
import StudentInfo from '@/pages/CourseInfo/StudentInfo';
import { identity } from 'lodash';
import { blobToJson } from '@/utils/export';
import ExportButton from '@/components/ExportButton';

const TableList: React.FC<{}> = () => {
  const { activityId, paperId } = history.location.query || {}
  const actionRef = useRef<ActionType>();
  const [tableData, setTableData] = useState([]);
  const [value, setValue] = useState(1);
  const [level, setLevel] = useState<any>([]);
  const [selectList, setSelectList] = useState<any>([]);
  const [selTableData, setSelTableData] = useState<any>([]);
  // const [tableData, setTableData] = useState<any>();
  const [selectedArr, setSeletedArr] = useState([]);
  const [currentLevel, setCurrentLevel] = useState();
  const [paperName, setPaperName] = useState();
  const [paperLevel, setPaperLevel] = useState();
  const [startTimeStr, setStartTimeStr] = useState();
  const [pageSize, setPageSize] = useState(20);
  const [pageNo, setPageNo] = useState(1);
  const [total, setTotal] = useState();
  
  // useEffect(() => {
  //   fetchSelData()
    
  // }, [currentLevel]);

  

  useEffect(() => {
    fetchData()
    fetchLevel()
  }, []);

  const fetchLevel = async () => {
      const res = await getValueAndTextList({code:'iqidao_duan'});
      const optionList = res.result.map((item: any) => ({
        label: `${item.text}`,
        value: `${item.value}`,
        key: `${item.value}`,
      }));
      console.log(optionList)
      setLevel(optionList);
      // setCurrentLevel(optionList[0].value)
    };

    const fetchData = async () => {
      const res = await paperList({paperId});
      setTableData(res.result.questions);
      setPaperName(res.result.paperName);
      setPaperLevel(res.result.level);
      setStartTimeStr(res.result.startTimeStr);
    };
    const fetchSelData = async () => {
      const res = await listByLevel({
        paperId,
        duan:currentLevel,
        pageSize: pageSize,
        pageNo: pageNo});
      setSelectList(res.result.records);
      setTotal(res.result.total);
    };
    const exportPaperList = async (id) => {
      // setLoading(true);
      const res = await downloadSgf({id});
      console.log(res)
      blobToJson(res, 'test');
      // setLoading(false);
    }
    const confirm = async (id:any) => {
      console.log(id);
      const result = await questionDelete({quizId:id,paperId});
      if (result.code === 200) {
        message.success('删除成功');
        fetchData()
      } else {
        message.error(result.message);
      }
    }
    const add = async () => {
      console.log(selectedArr)
      // return
      const res = await addBatch({paperId,quizIds:selectedArr});
      if (res.code === 200) {
        message.success('添加成功');
        if (actionRef.current) {
          actionRef.current.reload();
          fetchData()
        }
      } else {
        message.error(res.message);
      }
    };
    const onChange = (checkedValues: any) => {
      console.log('checked = ', checkedValues);
    };
    const onPageChange = (current: any, pageSize: any) => {
      console.log(current, pageSize);
      setPageSize(pageSize)
      setPageNo(current)
      fetchSelData()
    };
    
    const selColumns = [
      {
        title: '试题ID',
        dataIndex: 'id',
      },
      {
        title: '试题名称',
        dataIndex: 'name',
      },
      {
        title: '试题类型',
        dataIndex: 'typeDesc',
      },
      {
        title: '缩略图',
        dataIndex: 'thumb',
        render: (_, record) => <Image width={60} src={record.thumbnail} />
      }
    ];  
  const paperColumns = [
    {
      title: 'id编号',
      dataIndex: 'id',
    },
    {
      title: '试题名称',
      dataIndex: 'name',
    },
    {
      title: '题目类型',
      dataIndex: 'typeDesc',
    },
    {
      title: '缩略图',
      dataIndex: 'thumb',
      render: (_, record) => <Image width={60} src={record.thumbnail} />
    },
    {
      title: '难度',
      dataIndex: 'hardLevel',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        // <a
        //   style={{ marginRight: '20px' }}
        //   onClick={() => {
        //     // setModalVisible(true);
        //     // setModalType('edit');
        //     exportPaperList(record.id)
        //   }}
        // >
        //   下载
        // </a>,
        <ExportButton
        fileName={`${record.name}`}
        type="paperList"
        fileType="sgf"
        data={{id:record.id}}
        key="btn2"
        hideTime={true}
        render={<a style={{marginRight:20}}>下载</a>}
        />,
        // <ExportButton
        //       fileName={`${className} ${REVIEW_MAP[reviewStatus]}`}
        //       type="reviewList"
        //       fileType="xls"
        //       data={params}
        //       key="btn2"
        //     />,
        <Popconfirm
          placement="top"
          title={'确定删除吗?'}
          onConfirm={() => {
            confirm(record.id);
          }}
          okText="确定"
          cancelText="取消"
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];
  
 
  return (
    <div style={{backgroundColor: '#fff',padding:'20px'}}>
    <Descriptions>
        <Descriptions.Item label="试卷名称">{paperName}</Descriptions.Item>
        <Descriptions.Item label="难度">{paperLevel}</Descriptions.Item>
        <Descriptions.Item label="开始时间">{startTimeStr}</Descriptions.Item>
      </Descriptions>
      
      <Table columns={paperColumns} dataSource={tableData} pagination={false} scroll={{ y: 400 }}/>
      <div style={{display:'flex',justifyContent:'space-between',marginBottom:'20px',padding:'20px 0 10px',borderBottom:'1px solid #ccc'}}>
      <h3>选择等级</h3>
    </div>
      <Radio.Group
        value={currentLevel}
        optionType="button"
        buttonStyle="solid"
        onChange = {(e) => {
          console.log(e.target.value)
          setCurrentLevel(e.target.value);
          
          // currentLevel && fetchSelData()
          actionRef.current?.reload();
        }}
        options={level}
      ></Radio.Group>
      <div style={{display:'flex',justifyContent:'space-between',marginBottom:'20px',padding:'20px 0 10px',borderBottom:'1px solid #ccc'}}>
      <h3>选择试题</h3>
      <Button type="primary" onClick={add}>添加试题</Button>
    </div>
    <ProTable<{}>
          actionRef={actionRef}
          rowKey="id"
          // dataSource={selTableData}
          columns={selColumns}
          request={async params => {
            const msg = await listByLevel({
              paperId,
              duan:currentLevel,
              pageSize: params.pageSize,
              pageNo: params.current})
            let arr = []
            let res = msg.result.records
            res.map((item: any) => {
              if(item.select){
                arr.push(item.id)
              }
            });
            
            console.log(arr)
            setSeletedArr(arr);
            return {
              data: msg.result.records,
              success: true,
              total: msg.result.total
            }
          }}
          rowSelection={{
            onChange: (val: any,row: any) => {
              // for(let item of data){

              // }
              console.log(val)
              setSeletedArr(val);
            },
            selectedRowKeys: selectedArr,
          }}
          search={false}
          toolBarRender={false}
        />
      {/* <Checkbox.Group style={{ width: '100%' }} onChange={onChange}>
      <Row gutter={[10,20]}>
        {selectList.length > 0 && selectList.map((val, idx) => {
            return <Col span={6}>
              <Checkbox value={val.id}>
                <div style={{height:100,display:'flex'}}>
                <Image width={100} src={val.thumbnail} />
                <div style={{marginLeft:20}}>
                  <p>{val.id}</p>
                  <p>{val.typeDesc}</p>
                </div>
                </div>
                
              </Checkbox>
              </Col>
          })}
      </Row>
    </Checkbox.Group>
    
    <div style={{display:'flex',justifyContent:'flex-end'}}>
    <Pagination
      style={{float:'right'}}
      showSizeChanger
      onChange={onPageChange}
      defaultPageSize={20}
      current={pageNo}
      total={total}
    />
    </div> */}
    

    </div>
  );
};

export default TableList;
